package com.chenjunlin.shortlink.admin.common.web;

import com.chenjunlin.shortlink.admin.common.convention.exception.ClientException;
import com.chenjunlin.shortlink.admin.common.convention.result.Result;
import com.chenjunlin.shortlink.admin.common.convention.result.Results;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE) // 确保这个过滤器在最前面执行
public class ExceptionHandlerFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        try {
            chain.doFilter(request, response);
        } catch (ClientException e) {
            // 处理ClientException，返回统一的错误格式
            handleClientException(httpResponse, e);
        } catch (Exception e) {
            // 处理其他异常
            handleGenericException(httpResponse, e);
        }
    }

    private void handleClientException(HttpServletResponse response, ClientException e) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        // 使用与你GlobalExceptionHandler相同的响应格式
        Result<?> result = Results.failure(e);
        String jsonResponse = JSON.toJSONString(result);
        response.getWriter().write(jsonResponse);
    }

    private void handleGenericException(HttpServletResponse response, Exception e) throws IOException {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        Result<?> result = Results.failure();
        String jsonResponse = JSON.toJSONString(result);
        response.getWriter().write(jsonResponse);
    }
}